<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\AppException;
use App\Models\Answer;
use App\Models\Config;
use App\Models\Data;
use App\Models\Member;
use App\Models\MemberAnswer;
use App\Models\Problem;
use App\Models\ScoreRecord;
use App\Services\ExcelExportService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ProblemController extends BaseController
{
    /**
     * 首页数据
     * @param Request $request
     * @return array
     */
    public function index(Request $request)
    {
        $params = $request->all();
        //pc端展示
        $build = Problem::query();
        $pageSize = $request->input('pageSize', 50);
        $data = $build->paginate($pageSize);
        foreach ($data as $key => $value){
            $data[$key]['answer'] = Answer::query()->where('pid', $value['pid'])->get()->toArray();
        }

        return $this->success($data);
    }

    /**
     * 答题人获取题目api
     * @param $id
     * @param Request $request
     * @return array
     */
    public function memberProblemIndex($id, Request $request)
    {

        $member = Member::query()->where('member_id', $id)->first()->toArray();
        //查询出所有的题目

        $problem = Problem::query()->get()->toArray();
        $build = Problem::query();
        if ($member['num'] * 5 >= count($problem)){
            //已经全部答题结束了。随机抽取
            $pidArr = array_column($problem, 'pid');

            $randProblem = array_rand($pidArr , 5);
            $new = [];
            foreach ($pidArr as $key => $value){
                if (in_array($key, $randProblem)){
                    $new[] = $value;
                }
            }
            $data = $build->whereIn('pid', $new)->paginate(5);

        }else{

            $data = $build->paginate(5, $columns = ['*'], $pageName = 'page', $member['num'] + 1);
        }

        foreach ($data as $key => $value){
            $data[$key]['answer'] = Answer::query()->where('pid', $value['pid'])->get()->toArray();
        }

        return $this->success($data);

    }


    /**
     * @param $id  //完成答题人ID
     * @param Request $request
     * @return array
     */
    public function memberAnswer($id, Request $request)
    {
        $params = $request->all();

        //需要判断每日最多可以答题的次数
        $memberNum = MemberAnswer::query()
            ->where('uid', $id)
            ->whereBetween('created_at', [date('Y-m-d'), date('Y-m-d', strtotime('+1 day'))])
            ->get()->toArray();

        if (count($memberNum) > (Problem::PROBLEM_NUM) * 5){
            return $this->error([], '对不起，您今日答题次数已经达到上限');
        }

        $source = 10;//每个题目的分数
        $rightNum = 0;
        $content = $params['content'];
        foreach ($content as $key => $value){
            $memberAnswerData = [];
            $memberAnswerData['uid'] = $id;
            $memberAnswerData['pid'] = $value['pid'];
            $memberAnswerData['answer'] = $value['answer'];
            $memberAnswerData['member_answer'] = $value['correct'];
            $memberAnswerData['score'] = 0;
            $memberAnswerData['type'] = $value['type'];//类型单选还是多选
            if ($value['answer'] !=  $value['correct']){
                //答案错误
                $memberAnswerData['is_correct'] = Problem::PROBLEM_ERROR;
            }else{
                $memberAnswerData['score'] = Problem::PROBLEM_SCORE;
                $rightNum = $rightNum + 1;
                $memberAnswerData['is_correct'] = Problem::PROBLEM_RIGHT;
            }
            //答题明细表
            MemberAnswer::query()->create($memberAnswerData);
        }
        //积分统计

        Member::query()->where('member_id', $id)->increment('score', $rightNum * Problem::PROBLEM_SCORE);
        Member::query()->where('member_id', $id)->increment('all_score', $rightNum * Problem::PROBLEM_SCORE);
        //将轮次进行

        Member::query()->where('member_id', $id)->increment('num', 1);
        //记录下是否够满1500 .4500分
        $record = ScoreRecord::query()->where('uid', $id)->count();

        if ($record< 2){
            //需要记录
            $member = Member::query()->where('member_id', $id)->first()->toArray();
            if ($member['all_score'] >= 4500){
                //更改个人信息状态、、、如果是未达到情况下就改变状态
                if ($member['two_status'] == Member::STATUS_ZE){
                    Member::query()->where('member_id', $id)->update(['two_status' => Member::STATUS_ONE]);
                }
                ScoreRecord::query()->create(['uid' => $id, 'score' => 4500]);
            }
            if ($member['all_score'] >=1500 && $record == 0){
                //更改个人信息状态、、、如果是未达到情况下就改变状态

                if ($member['one_status'] == Member::STATUS_ZE){
                    Member::query()->where('member_id', $id)->update(['one_status' => Member::STATUS_ONE]);
                }

                ScoreRecord::query()->create(['uid' => $id, 'score' => 1500]);
            }

        }

        return $this->success(['score' => $rightNum * Problem::PROBLEM_SCORE], '完成答题');

    }

    /**
     * 题目上传api
     * @param Request $request
     * @return array
     * @throws AppException
     */
    public function import(Request $request)
    {
        $fileCharater = $request->file('file');
        $success_num = $error_num = 0;
        try {

            if ($fileCharater->isValid()) { //括号里面的是必须加的哦
                //如果括号里面的不加上的话，下面的方法也无法调用的

                //获取文件的扩展名
                $ext = $fileCharater->getClientOriginalExtension();

                if (!in_array($ext, ['xlsx', 'xls'])){
                    throw new AppException('import_type_is_fail');
                }

                //获取文件的绝对路径
                $path = $fileCharater->getRealPath();

                //定义文件名
                $filename = date('Y-m-d-H-i-s').'.'.$ext;

                //存储文件。disk里面的public。总的来说，就是调用disk模块里的public配置
                Storage::disk('public')->put($filename, file_get_contents($path));

                $directory = storage_path('app') . '/public';

                $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
                # 打开文件、载入excel表格
                $spreadsheet = $reader->load($directory . '/' . $filename);
                # 获取活动工作薄
                $sheet = $spreadsheet->getActiveSheet();

                # 获取总列数
                $highestColumn = $sheet->getHighestColumn();
                # 获取总行数
                $highestRow = $sheet->getHighestRow();
                # 列数 改为数字显示
                $highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);

                for($a = 2;$a <= $highestRow; $a++){
                    $i = 0;
                    $content = $sheet->getCellByColumnAndRow(1,$a)->getValue();
                    $type = $sheet->getCellByColumnAndRow(2,$a)->getValue();
                    $daan = $sheet->getCellByColumnAndRow(3,$a)->getValue();
                    $A = $sheet->getCellByColumnAndRow(4,$a)->getValue();
                    $B = $sheet->getCellByColumnAndRow(5,$a)->getValue();
                    $C = $sheet->getCellByColumnAndRow(6,$a)->getValue();
                    $D = $sheet->getCellByColumnAndRow(7,$a)->getValue();
                    $row_data = [];
                    for ($column = 1; $column <= $highestColumnIndex; $column++) {
                        $row_data[] = $sheet->getCellByColumnAndRow($column, $a)->getValue();
                        $i++;
                    }
                    if(!implode('',$row_data)){
                        //删除空行
                        continue;
                    }
                    if ($type == '单选题'){
                        $problemType = 1;
                    }else{
                        $problemType = 2;
                    }

                    $daan = explode('、', $daan);


                    $data = [
                        'sid' => 1,
                        'type' => $problemType,
                        'content' => $content,
                        'score' => 2,
                        'correct' => 0,
                        'status' => 0,
                    ];

                    //插入问题
                    $result = Problem::query()->create($data);

                    $correctStr = '';
                    if ($A != ''){
                        $insertData =[];
                        $insertData['content'] = $A;
                        $insertData['pid'] = $result->pid;
                        $insertData['is_correct'] = 1;

                        $resultA = Answer::query()->create($insertData);
                        if (in_array(1,$daan)){
                            $correctStr = $correctStr.',' . $resultA->aid;
                        }

                    }

                    if ($B != ''){
                        $insertData =[];
                        $insertData['content'] = $B;
                        $insertData['pid'] = $result->pid;
                        $insertData['is_correct'] = 1;

                        $resultB = Answer::query()->create($insertData);
                        if (in_array(2,$daan)){
                            $correctStr = $correctStr.',' . $resultB->aid;

                        }

                    }

                    if ($C != ''){
                        $insertData =[];
                        $insertData['content'] = $C;
                        $insertData['pid'] = $result->pid;
                        $insertData['is_correct'] = 1;

                        $resultC = Answer::query()->create($insertData);

                        if (in_array(3,$daan)){
                            $correctStr = $correctStr .',' . $resultC->aid;

                        }

                    }

                    if ($D != ''){
                        $insertData =[];
                        $insertData['content'] = $D;
                        $insertData['pid'] = $result->pid;
                        $insertData['is_correct'] = 1;

                        $resultD = Answer::query()->create($insertData);

                        if (in_array(4,$daan)){
                            $correctStr = $correctStr. ',' . $resultD->aid;

                        }

                    }
                    $correctStr = trim($correctStr, ',');

                    //进行更改题目答案表

                    Problem::query()->where('pid', $result->pid)->update(['correct' => $correctStr]);

                    if ($result){
                        $success_num = $success_num +1;
                    }else{
                        $error_num = $error_num + 1;
                    }
                }
            }
            $data['success_num'] = $success_num;
            $data['error_num'] = $error_num;
            return $this->success($data);

        } catch (\ Exception $exception) {
            throw new AppException($exception->getMessage());

        }

    }


    public function problemCheck($id, Request $request)
    {
        $member = Member::query()->where('member_id', $id)->first()->toArray();


        $today = MemberAnswer::query()
            ->where('uid', $id)
            ->whereBetween('created_at', [date('Y-m-d'), date('Y-m-d', strtotime('+1 day'))])
            ->get()->toArray();
        $status = 0;
        if ($member['num'] >= 20){
            if ($member['hundred_reward'] == 1){
                //领取了
                if (count($today) >= 25){
                    $status =2;
                }

            }else{
                $status = 1;

            }
        }

        if (count($today) >= 25){

            $status = 2;
        }

        return $this->success(['status' => $status], '获取成功');

    }






}